<?php
namespace MyAdmin\Controller;

use Think\Controller;
/**
 * 已废弃
 */
class AdminsController extends CommonController
{
  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  //管理员模块 只有最上级管理员可以查看
  public function index()
  {
    $this->display();
  }

  public function edit()
  {
    $admin_id = $this->admin_id;
    $admin = M('admins')->where("id = $admin_id")->find();
    $this->assign("admin", $admin);

    $this->display();
  }

  public function update()
  {
    if (!IS_AJAX && !IS_POST) {
      return_data("error", "admins.update.error");
    }

    $data = I('post.');
    $name = trim(I('post.name'));
    $phone = trim(I('post.phone'));
    $passwd = trim(I('post.old_passwd'));
    $new_passwd = trim(I('post.passwd'));
    if (!$passwd) {
      return_data("error", "error.admin.password");
    }
    $id = $data['id'];
    $admin = M("admins")->where(array('id' => $id))->find();
    if (!$admin) {
      return_data("error", "error.admin.invalid");
    }
    //验证合法性
    if (!$name) {
      return_data("error", "error.admin.name.blank");
    }

    if ($admin['phone'] != $phone) {
      $phone_check = M('admins')->where("phone='$phone'")->find();
      if ($phone_check) {
        return_data("error", "error.admin.phone.exist");
      }
    }
    $old_passwd = $admin['passwd'];
    $salt = $admin['salt'];
    if ($old_passwd != md5(md5($passwd).$salt)) {
      return return_data("error", "update.admin.password.error");
    }
    if ($new_passwd) {
      $data['salt'] = random(6, 1);
      $data['passwd'] = md5(md5($new_passwd).$data['salt']);
    }

    //手机验证--唯一性--11位
    if (strlen($phone) != 11) {
      return_data("error", "update.phone.eleven.number");
    }
    if (!preg_match("/^1[0-9]{10}$/", $phone)) {
      return_data("error", "update.phone.error");
    }

    $data["updated_at"] = $this->now_time;
    $result = M('admins')->where(array('id' => $id))->save($data);

    if ($result) {
      return_data("update", "更新成功");
    } else {
      return_data("error", "更新失败");
    }
  }

  public function app_edit()
  {
    $admin = $this->admin_info;

    if ($this->app_id) {
      $app = M('apps')->where("id = {$this->app_id}")->find();
      $this->assign("app", $app);
    }

    $this->display();
  }

  public function app_show()
  {
    $admin = $this->admin_info;

    if ($this->app_id) {
      $app = M('apps')->where("id = {$this->app_id}")->find();

      $this->assign("app", $app);
    }

    $this->display();
  }

  public function app_update()
  {
    $admin = $this->admin_info;

    $data = I('post.');
    //TODO:唯一性检查
    $data = M('apps')->create($data);
    $data['updated_at'] = $this->now_time;
    if (!$data['id'] && !$this->app_id) {
      M('apps')->add($data);
    } else {
      M('apps')->where("id = {$this->app_id}")->save($data);
    }

    return_data("update", "更新成功");
  }

  public function app_export()
  {
    $app_info = $this->app_info;
    copy("app.sample.js", "app.js");
    $file_url = 'app.js';
    $file=fopen($file_url, 'a')or die("Unable to open file!");
    $txt = "app_id: ".$this->app_id.",\n app_name: '$app_info[name]',\n app_kfwechat: '$app_info[kfwechat]',\n app_kfphone: '$app_info[kfphone]'\n})";
    fwrite($file, $txt);
    fclose($file_url);
    $file=fopen($file_url, 'r');
		//    获取文件路径中最后的文件名部分
    $file_name=basename($file_url);
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    header("Accept-Length: ".filesize($file_url));
    header("Content-Disposition: attachment; filename=".$file_name);
		//    这里一定要使用echo 进行输出，否则下载的文家是空白的
    echo fread($file, filesize($file_url));
		//    断开链接
    fclose($file_url);
    @unlink($file_url);
  }

  public function adverts_index()
  {
    $adverts = M('adverts')->where("app_id={$this->app_id}")->order("orderby asc")->select();

    foreach ($adverts as $key => &$value) {
      $value['created_at'] = local_time($value['created_at']);
      $value['updated_at'] = local_time($value['updated_at']);

      switch ($value['status']) {
        case 1:
          $value['status_str'] = "开启";
          break;
        case 2:
          $value['status_str'] = "关闭";
          break;
        default:
          $value['status_str'] = "未知";
          break;
        }
    }

    $this->assign("adverts", $adverts);

    $this->display();
  }

  public function advert_new()
  {
    $this->display();
  }

  public function advert_edit()
  {
    $id = I('id');
    $advert = M('adverts')->where("id=$id")->find();

    $this->assign("advert", $advert);
    $this->display();
  }

  public function advert_create()
  {
    $data = I('post.');
    if ($_FILES) {
      //上传图片
      $upyun_config = D('admins')->get_app_upyun_config($this->app_info);
      $upload = new \Think\Upload(array(), 'Upyun', $upyun_config);// 实例化上传类
        $upload->rootPath = './'; //设置上传根目录，这里直接填写'./'即可
        $upload->savePath = ''; //设置文件保存的子目录，如果设置的话，记得要以'/'结束
        // $upload->autoSub = FALSE; //取消自动子目录保存文件，这个根据需求来设置
        $info   =   $upload->upload(); //上传文件

        if (!$info) {
          return_data("error", "upload.files.error", $upload->getError());
        } else {
          foreach ($info as $file) {
            // $file_arr[]=$upyun_bucket_host."/".$file['savepath'].$file['savename'];
            $file_arr[] = "$upyun_config[endpoint]/$file[savepath]$file[savename]";
          }
        }

      if ($info) {
        $img_url = $file_arr[0];
        $data['image'] = $img_url;
      } else {
        return_data("error", "upload.files.error");
      }
    }
    if ($data['link']) {
      $data['link'] = htmlspecialchars_decode($data['link']);
    }
    $data['app_id'] = $this->app_id;
    $data['created_at'] = $data['updated_at'] = $this->now_time;
    $data = M('adverts')->create($data);
    $result = M('adverts')->add($data);
    if ($result) {
      return_data("update", "操作成功");
    } else {
      return_data("error", "操作失败");
    }
  }

  public function advert_update()
  {
    $data = I('post.');
    if ($_FILES) {
      //上传图片
      $upyun_config = D('admins')->get_app_upyun_config($this->app_info);
      $upload = new \Think\Upload(array(), 'Upyun', $upyun_config);// 实例化上传类
        $upload->rootPath = './'; //设置上传根目录，这里直接填写'./'即可
        $upload->savePath = ''; //设置文件保存的子目录，如果设置的话，记得要以'/'结束
        // $upload->autoSub = FALSE; //取消自动子目录保存文件，这个根据需求来设置
        $info = $upload->upload(); //上传文件

        if (!$info) {
          return_data("error", "upload.files.error", $upload->getError());
        } else {
          foreach ($info as $file) {
            // $file_arr[]=$upyun_bucket_host."/".$file['savepath'].$file['savename'];
            $file_arr[] = "$upyun_config[endpoint]/$file[savepath]$file[savename]";
          }
        }

      if ($info) {
        $img_url = $file_arr[0];
        $data['image'] = $img_url;
      } else {
        return_data("error", "文件上传错误");
      }
    }
    if ($data['link']) {
      $data['link'] = htmlspecialchars_decode($data['link']);
    }
    $data['updated_at'] = $this->now_time;
    $result = M('adverts')->where("id=$data[id]")->save($data);
    if ($result) {
      return_data("update", "更新成功");
    } else {
      return_data("error", "更新失败");
    }
  }

  public function export_xcx()
  {
    $root =  THINK_PATH.'../';
    $path = "{$root}xcx_app";
    $tmp_path = "{$root}xcx.zip";

    if (file_exists($tmp_path)) {
      unlink($tmp_path);
    }

    unlink("{$path}/app.js");
    copy("{$root}/app.sample.js", "{$path}/app.js");

    $app_info = $this->app_info;
    $config = "app_id: {$this->app_id},\n  app_name: '{$app_info[name]}',\n  app_kfwechat: '{$app_info[kfwechat]}',\n  app_kfphone: '{$app_info[kfphone]}'\n});";
    file_put_contents("{$path}/app.js", $config, FILE_APPEND);

    Vendor("Zip.HZip");
    \HZip::zipDir($path, $tmp_path);

    header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
    header("Cache-Control: max-age=0");
    header("Content-Description: File Transfer");
    header("Content-Type: application/force-download");
    header('Content-disposition: attachment; filename=xcx.zip');
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");
    header('Content-Length: ' . filesize($tmp_path));
    @readfile($tmp_path);
  }
}
